<template>
    <div v-loading="loading" element-loading-text="拼命加载中">
        <div class="content_top">
            <el-row>
                <el-col :span="12">
                    <span v-if="villageId === null">新增小区</span>
                    <span v-if="villageId !== null">修改小区</span>
                </el-col>
                <el-col :span="12" style="text-align: right">
                    <el-button icon="el-icon-back" type="default" circle size="mini" @click="back"></el-button>
                </el-col>
            </el-row>
        </div>

        <div class="content">

            <el-row>
                <el-col :span="12" class="amap-page-container">
                    <div class="search-box">
                        <el-row>
                            <el-col :span="7">
                                <div class="el-vue-search-box-container">
                                    <div class="search-box-wrapper">
                                        <el-select v-model="city" filterable placeholder="请选择" @change="cityChange">
                                            <el-option v-for="item in citys" :key="item.id" :label="item.name" :value="item.id">
                                                <span style="float: left">{{ item.name }}</span>
                                                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.pinyin }}</span>
                                            </el-option>
                                        </el-select>
                                    </div>
                                </div>
                            </el-col>
                            <el-col :span="17">
                                <el-amap-search-box :search-option="map.searchOption" :on-search-result="onSearchResult">
                                </el-amap-search-box>
                            </el-col>
                        </el-row>
                    </div>
                    <el-amap class="amap" :amapManager="map.amapManager" :events="map.events" :center="map.center" :zoom="map.zoom">
                    </el-amap>
                </el-col>
                <el-col :span="12" style="padding-left: 20px;">
                    <el-form ref="form" :model="data" :rules="rules" label-width="95px" size="mini" style="width: 50%;">
                        <el-form-item label="省份：" prop="provinceName">
                            <el-input v-model="data.provinceName"></el-input>
                        </el-form-item>
                        <el-form-item label="城市：" prop="cityName">
                            <el-input v-model="data.cityName"></el-input>
                        </el-form-item>
                        <el-form-item label="区/县：" prop="districtName">
                            <el-input v-model="data.districtName"></el-input>
                        </el-form-item>
                        <el-form-item label="社区:" prop="communityId">
                          <el-select size="mini" placeholder="请选择" class="form-item" v-model="data.communityId" clearable style="width: 100%">
                            <el-option v-for="item in communityItems" :key="item.id" :label="item.name" :value="item.id"></el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="小区名称：" prop="name">
                            <el-input v-model="data.name"></el-input>
                        </el-form-item>
                        <el-form-item label="小区地址：" prop="address">
                            <el-input v-model="data.address"></el-input>
                        </el-form-item>
                        <el-form-item label="经度：" prop="longitude">
                            <el-input v-model="data.longitude" readonly></el-input>
                        </el-form-item>
                        <el-form-item label="纬度：" prop="latitude">
                            <el-input v-model="data.latitude" readonly></el-input>
                        </el-form-item>
                        <el-form-item label="备注：" prop="remark">
                            <el-input type="textarea" v-model="data.remark"></el-input>
                        </el-form-item>
                        <el-form-item style="text-align: center">
                            <el-button type="primary" @click="onSubmit">保存</el-button>
                            <el-button @click="$router.back()">取消</el-button>
                        </el-form-item>
                    </el-form>

                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script>
    import {areaList} from '@/api/base/area'
    import {communityItems} from '@/api/base/community'
    import {addVillage, modifyVillage, villageInfo} from '@/api/base/village'
    import {AMapManager} from "vue-amap"

    let amapManager = new AMapManager();
    let geocoder = new AMap.Geocoder();

    export default {
        name: 'VillageSave',
        data() {
            let _this = this
            return {
                loading: false,
                citys: [],
                city: null,
                map: {
                    amapManager,
                    searchOption: {
                        city: '长春市',
                        citylimit: true
                    },
                    zoom: 11,
                    center: [121.59996, 31.197646],
                    maker: null,
                    events: {
                        click(e) {
                            _this.setMarker({lng: e.lnglat.lng, lat: e.lnglat.lat}, 2)
                        }
                    }
                },
                communityItems: [],
                villageId: null,
                data: {
                    provinceName: null,
                    cityName: null,
                    districtName: null,
                    communityId: null,
                    name: null,
                    longitude: null,
                    latitude: null,
                    address: null,
                    remark: null,
                },
                rules: {
                    provinceName: [
                        {required: true, message: '请输入省份名称', trigger: 'blur'},
                        {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
                    ],
                    cityName: [
                        {required: true, message: '请输入城市名称', trigger: 'blur'},
                        {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
                    ],
                    districtName: [
                        {min: 0, max: 50, message: '长度在 0 到 50 个字符', trigger: 'blur'}
                    ],
                    communityId: [
                        {required: true, message: '请选择社区', trigger: 'blur'},
                    ],
                    name: [
                        {required: true, message: '请输入小区名称', trigger: 'blur'},
                        {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
                    ],
                    longitude: [
                        {required: true, message: '请输入经度', trigger: 'blur'}
                    ],
                    latitude: [
                        {required: true, message: '请输入纬度', trigger: 'blur'}
                    ],
                    address: [
                        {min: 0, max: 100, message: '长度在 0 到 50 个字符', trigger: 'blur'}
                    ],
                    remark: [
                        {min: 0, max: 255, message: '长度在 3 到 50 个字符', trigger: 'blur'}
                    ],
                }
            }
        },
        mounted() {
            this.loadAreaList()
            this.loadCommunity();
            this.villageId = window.localStorage.getItem("villageId")
            if (this.villageId) {
                this.loadVillageInfo()
            }
        },
        methods: {
            back () {
                this.$router.back()
            },
            async loadCommunity() {
              let res = await communityItems()
              this.communityItems = res.data;
            },
            async loadAreaList() {
                let res = await areaList(2)
                this.citys = res.data
                let _city = this.citys.find(item => {
                    return item.name === '长春市'
                });
                if (this.villageId === null) {
                    this.city = _city.id
                    this.map.searchOption.city = _city.name
                    this.map.center = [_city.longitude, _city.latitude]
                }
            },
            async loadVillageInfo() {
                this.loading = true
                let res = await villageInfo(this.villageId)
                this.loading = false
                this.data = res.data

                this.city = this.data.city
                this.map.searchOption.city = this.data.cityName
                this.map.center = [this.data.longitude, this.data.latitude]

                if (this.map.marker) {
                    amapManager.getMap().remove(this.map.marker)
                    this.map.marker = null
                }
                this.map.zoom = 16
                this.map.marker = new AMap.Marker({
                    position: this.map.center,
                });
                this.map.marker.setMap(amapManager.getMap());
                this.map.marker.setMap(amapManager.getMap());
                this.map.marker.setAnimation('AMAP_ANIMATION_BOUNCE');
            },
            cityChange() {
                let _city = this.citys.find(item => {
                    return item.id === this.city
                });
                this.city = _city.id
                this.map.searchOption.city = _city.name
                this.map.center = [_city.longitude, _city.latitude]
                this.map.zoom = 11
            },
            onSearchResult(pois) {
                if (pois.length > 0) {
                    let poi = pois[0]
                    this.data.name = poi.name
                    this.data.address = poi.address
                    this.setMarker({lng: poi.lng, lat: poi.lat}, 1)
                }
            },
            setMarker(lnglat, type) {
                if (this.map.marker) {
                    amapManager.getMap().remove(this.map.marker)
                    this.map.marker = null
                }
                this.map.center = [lnglat.lng, lnglat.lat]
                this.map.zoom = 16
                this.map.marker = new AMap.Marker({
                    position: this.map.center,
                });
                this.map.marker.setMap(amapManager.getMap());
                this.map.marker.setMap(amapManager.getMap());
                this.map.marker.setAnimation('AMAP_ANIMATION_BOUNCE');

                this.data.longitude = lnglat.lng
                this.data.latitude = lnglat.lat

                let _this = this;
                geocoder.getAddress(this.map.center, function (status, result) {
                    if (status === 'complete' && result.regeocode) {
                        let _p = result.regeocode.addressComponent.province;
                        _this.data.provinceName = _p.replace("市", "")
                        _this.data.cityName = result.regeocode.addressComponent.city === '' ? result.regeocode.addressComponent.province : result.regeocode.addressComponent.city
                        _this.data.districtName = result.regeocode.addressComponent.district
                        if (type === 2) {
                            _this.data.name = result.regeocode.formattedAddress.replace(_this.data.provinceName, '').replace(_this.data.cityName, '').replace(_this.data.districtName, '')
                            _this.data.address = result.regeocode.addressComponent.street + result.regeocode.addressComponent.streetNumber
                        }
                        _this.$nextTick()
                    }
                });
            },
            onSubmit() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        this.save()
                    } else {
                        return false;
                    }
                });
            },
            async save() {
                this.loading = true;
                let res = null;
                if (this.villageId === null) {
                    res = await addVillage(this.data)
                } else {
                    res = await modifyVillage(this.villageId, this.data)
                }

                this.loading = false
                if (res.code !== '0') {
                    return this.$notify.error({title: '消息', message: res.message})
                }
                this.$notify({title: '消息', message: '保存成功', type: 'success'});
                if (!this.villageId) {
                    this.$refs.form.resetFields();
                }
            }
        }
    }
</script>

<style scoped>

    .amap {
        width: 100%;
        height: 600px;
        border: 1px solid #E4E7ED;
    }

    .search-box {
        position: absolute;
        top: 15px;
        left: 20px;
    }

    .amap-page-container {
        position: relative;
    }

</style>
